/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.sciTechnologyDemand.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.activity.domain.dto.ActivityDto;
import com.fzhucc.modules.appletBanner.domain.dto.AppletBannerDto;
import com.fzhucc.modules.appletShow.domain.dto.CmsServiceDto;
import com.fzhucc.modules.sciPersonnelInfo.domain.*;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.SciPersonnelInfoDto;
import com.fzhucc.modules.sciPersonnelInfo.repository.*;
import com.fzhucc.modules.sciPersonnelInfo.service.mapstruct.SciPersonnelInfoMapper;
import com.fzhucc.modules.sciPersonnelInfo.service.mapstruct.SciPersonnelInfoMateMapper;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemand;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemandMate;
import com.fzhucc.modules.sciTechnologyDemand.domain.dto.*;
import com.fzhucc.modules.sciTechnologyDemand.repository.SciTechnologyDemandRepository;
import com.fzhucc.modules.sciTechnologyDemand.service.mapstruct.SciTechnologyDemandMapper;
import com.fzhucc.utils.ValidationUtil;
import com.fzhucc.utils.FileUtil;
import com.fzhucc.utils.PageUtil;
import com.fzhucc.utils.QueryHelp;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.sciTechnologyDemand.repository.SciTechnologyDemandMateRepository;
import com.fzhucc.modules.sciTechnologyDemand.service.mapstruct.SciTechnologyDemandMateMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-12-15
 **/
@Service
@RequiredArgsConstructor
public class SciTechnologyDemandMateService {

    private final SciTechnologyDemandMateRepository sciTechnologyDemandMateRepository;

    private final SciPersonnelInfoWeRepository sciPersonnelInfoWeRepository;

    private final SciPersonnelInfoLessonRepository sciPersonnelInfoLessonRepository;

    private final SciPersonnelInfoResultRepository sciPersonnelInfoResultRepository;
    private final SciTechnologyDemandMateMapper sciTechnologyDemandMateMapper;

    private final SciTechnologyDemandRepository tdRepository;

    private final SciPersonnelInfoRepository spRepository;

    private final SciTechnologyDemandMapper tdMapper;

    private final SciPersonnelInfoMateMapper sciPersonnelInfoMateMapper;

    private final SciPersonnelInfoMapper spMapper;

    private final SciPersonnelInfoMateRepository sciPersonnelInfoMateRepository;

    @Value("${sci.audit.shtg}")
    public String shtg;

    public Map<String, Object> queryAll(SciTechnologyDemandMateQueryCriteria criteria, Pageable pageable) {
        if (criteria.getName() != null) {
            Page<SciTechnologyDemandMate> page2 = sciTechnologyDemandMateRepository.findAllWithOutParmByLikeMName(criteria.getTdId(), "%" + criteria.getName() + "%", pageable);
            Page<SciTechnologyDemandMateDto> map = page2.map(sciTechnologyDemandMateMapper::toDto);
            List<SciTechnologyDemandMateDto> list = map.getContent();
            if (list != null && list.size() > 0) {
                for (SciTechnologyDemandMateDto dto : list) {
                    Integer spId = dto.getSpId();
                    Optional<SciPersonnelInfo> res = spRepository.findById(spId);
                    if (res.isPresent()) {
                        SciPersonnelInfo sciPersonnelInfo = res.get();
                        dto.setSciPersonnelInfoDto(spMapper.toDto(sciPersonnelInfo));
                    }

                    Integer tdId = dto.getTdId();
                    Optional<SciTechnologyDemand> res2 = tdRepository.findById(tdId);
                    if (res2.isPresent()) {
                        SciTechnologyDemand sciTechnologyDemand = res2.get();
                        dto.setSciTechnologyDemandDto(tdMapper.toDto(sciTechnologyDemand));
                    }
                }
            }
            return PageUtil.toPage(map);
        }else{
            Page<SciTechnologyDemandMate> page = sciTechnologyDemandMateRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
            Page<SciTechnologyDemandMateDto> map = page.map(sciTechnologyDemandMateMapper::toDto);
            List<SciTechnologyDemandMateDto> list = map.getContent();
            if (list != null && list.size() > 0) {
                for (SciTechnologyDemandMateDto dto : list) {
                    Integer spId = dto.getSpId();
                    Optional<SciPersonnelInfo> res = spRepository.findById(spId);
                    if (res.isPresent()) {
                        SciPersonnelInfo sciPersonnelInfo = res.get();
                        dto.setSciPersonnelInfoDto(spMapper.toDto(sciPersonnelInfo));
                    }

                    Integer tdId = dto.getTdId();
                    Optional<SciTechnologyDemand> res2 = tdRepository.findById(tdId);
                    if (res2.isPresent()) {
                        SciTechnologyDemand sciTechnologyDemand = res2.get();
                        dto.setSciTechnologyDemandDto(tdMapper.toDto(sciTechnologyDemand));
                    }
                }
            }
            return PageUtil.toPage(map);
        }
    }

    public List<SciTechnologyDemandMateDto> queryAll(SciTechnologyDemandMateQueryCriteria criteria) {
        return sciTechnologyDemandMateMapper.toDto(sciTechnologyDemandMateRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public List<SciPersonnelInfoDto> getAllMateSciPersonnelInfo(String name) {
        if (name == null) {
            //就查询前50条数据
            List<SciPersonnelInfo> normal = spRepository.findNormalTop(shtg);
            List<SciPersonnelInfoDto> sciPersonnelInfoDtos = spMapper.toDto(normal);

            if (sciPersonnelInfoDtos != null && sciPersonnelInfoDtos.size() > 0) {
                for (SciPersonnelInfoDto sciPersonnelInfoDto : sciPersonnelInfoDtos) {
                    String matype = sciPersonnelInfoDto.getMatype();
                    if (matype != null && matype.contains(";")) {
                        String[] array = matype.split(";");
                        sciPersonnelInfoDto.setMatypes(array);
                    } else {
                        String[] array = {};
                        sciPersonnelInfoDto.setMatypes(array);
                    }
                    String orgArea = sciPersonnelInfoDto.getOrgArea();
                    if (orgArea != null && orgArea.contains(";")) {
                        String[] array = orgArea.split(";");
                        sciPersonnelInfoDto.setOrgAreas(array);
                    } else {
                        String[] array = {};
                        sciPersonnelInfoDto.setOrgAreas(array);
                    }

                    Integer id = sciPersonnelInfoDto.getId();
                    List<SciPersonnelInfoResult> results = sciPersonnelInfoResultRepository.findBySpId(id);
                    sciPersonnelInfoDto.setListResult(results);
                    List<SciPersonnelInfoLesson> list2 = sciPersonnelInfoLessonRepository.findBySpId(id);
                    sciPersonnelInfoDto.setListLesson(list2);
                    List<SciPersonnelInfoWe> list3 = sciPersonnelInfoWeRepository.findBySpId(id);
                    sciPersonnelInfoDto.setListWe(list3);
                }
            }
            return sciPersonnelInfoDtos;
        } else {
            List<SciPersonnelInfo> list = spRepository.findNormalByLikeName(shtg, "%" + name + "%");
            List<SciPersonnelInfoDto> sciPersonnelInfoDtos = spMapper.toDto(list);

            if (sciPersonnelInfoDtos != null && sciPersonnelInfoDtos.size() > 0) {
                for (SciPersonnelInfoDto sciPersonnelInfoDto : sciPersonnelInfoDtos) {
                    String matype = sciPersonnelInfoDto.getMatype();
                    if (matype != null && matype.contains(";")) {
                        String[] array = matype.split(";");
                        sciPersonnelInfoDto.setMatypes(array);
                    } else {
                        String[] array = {};
                        sciPersonnelInfoDto.setMatypes(array);
                    }
                    String orgArea = sciPersonnelInfoDto.getOrgArea();
                    if (orgArea != null && orgArea.contains(";")) {
                        String[] array = orgArea.split(";");
                        sciPersonnelInfoDto.setOrgAreas(array);
                    } else {
                        String[] array = {};
                        sciPersonnelInfoDto.setOrgAreas(array);
                    }

                    Integer id = sciPersonnelInfoDto.getId();
                    List<SciPersonnelInfoResult> results = sciPersonnelInfoResultRepository.findBySpId(id);
                    sciPersonnelInfoDto.setListResult(results);
                    List<SciPersonnelInfoLesson> list2 = sciPersonnelInfoLessonRepository.findBySpId(id);
                    sciPersonnelInfoDto.setListLesson(list2);
                    List<SciPersonnelInfoWe> list3 = sciPersonnelInfoWeRepository.findBySpId(id);
                    sciPersonnelInfoDto.setListWe(list3);
                }
            }
            return sciPersonnelInfoDtos;
        }
    }

    @Transactional
    public SciTechnologyDemandMateDto findById(Integer id) {
        SciTechnologyDemandMate sciTechnologyDemandMate = sciTechnologyDemandMateRepository.findById(id).orElseGet(SciTechnologyDemandMate::new);
        ValidationUtil.isNull(sciTechnologyDemandMate.getId(), "SciTechnologyDemandMate", "id", id);
        return sciTechnologyDemandMateMapper.toDto(sciTechnologyDemandMate);
    }

    @Transactional(rollbackFor = Exception.class)
    public SciTechnologyDemandMateDto create(SciTechnologyDemandMate resources) {
        Integer tdId = resources.getTdId();
        Optional<SciTechnologyDemand> res = tdRepository.findById(tdId);
        if (!res.isPresent()) {
            throw new BadRequestException("未找到对应的企业需求");
        }
        Integer spId = resources.getSpId();
        Optional<SciPersonnelInfo> res2 = spRepository.findById(spId);
        if (!res2.isPresent()) {
            throw new BadRequestException("未找到对应的劳模工匠");
        }
        //查询库里是否有 spid 及 tdid相同的记录 有则跳过
        List<SciTechnologyDemandMate> lists = sciTechnologyDemandMateRepository.findBySpIdTdId(spId, tdId);
        if (lists != null && lists.size() > 0) {
            throw new BadRequestException("已存在该劳模工匠,请选择其他劳模工匠");
        } else {
            SciTechnologyDemand sciTechnologyDemand = res.get();
            SciPersonnelInfo sciPersonnelInfo = res2.get();
            String sptechnology = sciPersonnelInfo.getTechnology();
            String tdtechnology = sciTechnologyDemand.getTechnology();
            String spretype = sciPersonnelInfo.getRetype();
            String tdretype = sciTechnologyDemand.getRetype();
            if (sptechnology != null && tdtechnology != null && sptechnology.equals(tdtechnology)) {
                resources.setTechnology(tdtechnology);
            }
            if (spretype != null && tdretype != null && spretype.equals(tdretype)) {
                resources.setRetype(spretype);
            }
            if (sptechnology != null && tdtechnology != null && (!sptechnology.equals(tdtechnology))) {
                resources.setTechnology("劳模工匠:" + sptechnology + ";企业需求:" + tdtechnology);
            }
            if (spretype != null && tdretype != null && (!spretype.equals(tdretype))) {
                resources.setRetype("劳模工匠:" + spretype + ";企业需求:" + tdretype);
            }
            resources.setMatesort(0);//手动添加表示为最重要的 优选顺序第一
            resources.setIsSelect(0);
            resources.setMateTime(new Timestamp(new Date().getTime()));
            return sciTechnologyDemandMateMapper.toDto(sciTechnologyDemandMateRepository.save(resources));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public List<SciPersonnelInfoDto> mate(MateDto dto) {
        List<SciPersonnelInfoDto> result = new ArrayList<SciPersonnelInfoDto>();
        Integer tdId = dto.getTdId();
        Optional<SciTechnologyDemand> res = tdRepository.findById(tdId);
        if (!res.isPresent()) {
            throw new BadRequestException("未找到对应的企业需求");
        }
        SciTechnologyDemand sciTechnologyDemand = res.get();
        String technology = sciTechnologyDemand.getTechnology();
        String retype = sciTechnologyDemand.getRetype();
        String sretype = "%" + retype + "%";//因为劳模表中此变量为数组形式则符合条件就展示出来
        List<SciPersonnelInfo> list = spRepository.findNormalByTechnologyRetype(technology, sretype, shtg);
        if (list != null && list.size() > 0) {
            for (SciPersonnelInfo sciPersonnelInfo : list) {
                //查询库里是否有 spid 及 tdid相同的记录 有则跳过
                List<SciTechnologyDemandMate> lists = sciTechnologyDemandMateRepository.findBySpIdTdId(sciPersonnelInfo.getId(), tdId);
                if (lists != null && lists.size() > 0) {
                    for (SciTechnologyDemandMate mate : lists) {
                        Integer spId = mate.getSpId();
                        Optional<SciPersonnelInfo> resExpert = spRepository.findById(spId);
                        if (resExpert.isPresent()) {
                            SciPersonnelInfo sciPersonnelInfo1 = resExpert.get();
                            SciPersonnelInfoDto sciPersonnelInfoDto = spMapper.toDto(sciPersonnelInfo1);
                            result.add(sciPersonnelInfoDto);
                        }
                    }
                } else {
                    SciTechnologyDemandMate sciTechnologyDemandMate = new SciTechnologyDemandMate();
                    sciTechnologyDemandMate.setTechnology(sciPersonnelInfo.getTechnology());
                    sciTechnologyDemandMate.setRetype(sciPersonnelInfo.getMatype());
                    sciTechnologyDemandMate.setMateTime(new Timestamp(new Date().getTime()));
                    sciTechnologyDemandMate.setSpId(sciPersonnelInfo.getId());
                    sciTechnologyDemandMate.setTdId(tdId);
                    SciTechnologyDemandMate save = sciTechnologyDemandMateRepository.save(sciTechnologyDemandMate);
                    Integer spId = save.getSpId();
                    Optional<SciPersonnelInfo> resExpert = spRepository.findById(spId);
                    if (resExpert.isPresent()) {
                        SciPersonnelInfo sciPersonnelInfo1 = resExpert.get();
                        SciPersonnelInfoDto sciPersonnelInfoDto = spMapper.toDto(sciPersonnelInfo1);
                        result.add(sciPersonnelInfoDto);
                    }
                }
            }
            return result;
        } else {
            throw new BadRequestException("未匹配到符合的对应类型");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> mateWithMateSort(SciTechnologyDemandMateQueryCriteria criteria, Pageable pageable) {
        //TODO
        // 匹配的优先级
        // 1所属工会+技术领域+需求类别；
        // 2技术领域+需求类别；
        // 3技术领域
        //List<SciPersonnelInfoDto> result = new ArrayList<SciPersonnelInfoDto>();
        Integer tdId = criteria.getTdId();
        Optional<SciTechnologyDemand> res = tdRepository.findById(tdId);
        if (!res.isPresent()) {
            throw new BadRequestException("未找到对应的企业需求");
        }
        SciTechnologyDemand sciTechnologyDemand = res.get();
        String technology = sciTechnologyDemand.getTechnology();//技术领域
        String retype = sciTechnologyDemand.getRetype();//需求类别
        String orgArea = sciTechnologyDemand.getOrgArea();//需求的orgArea 例福建省;福州市;马尾区
        String sretype = "%" + retype + "%";
        String sorgArea = "%" + orgArea + "%";

        //todo 先查询被选中的list 此 list不再新增
        List<Integer> listModelIds = new ArrayList<Integer>();
        List<SciTechnologyDemandMate> isSelect = sciTechnologyDemandMateRepository.findIsSelect(tdId);
        if (isSelect != null && isSelect.size() > 0) {
            for (SciTechnologyDemandMate mate : isSelect) {
                listModelIds.add(mate.getSpId());
            }
        }


        // 先按顺序查询记录  最后统一查询
        List<SciPersonnelInfo> list = spRepository.findNormalLikeTechnologyRetypeLikeRetypeLikeOrgArea(technology, sretype, sorgArea, shtg);
        //特殊情况 查询匹配2的  如果在第一个查询中含有2的  则更新此记录为1
        List<SciTechnologyDemandMate> byTdIdWithMateSortSecond = sciTechnologyDemandMateRepository.findByTdIdWithMateSortSecond(tdId);
        if (byTdIdWithMateSortSecond != null && byTdIdWithMateSortSecond.size() > 0 && list != null && list.size() > 0) {
            for (SciTechnologyDemandMate mate : byTdIdWithMateSortSecond) {
                int spId = mate.getSpId();
                for (SciPersonnelInfo sciPersonnelInfo : list) {
                    Integer id = sciPersonnelInfo.getId();
                    if (spId == id) {
                        if (!listModelIds.contains(spId)){
                            //相同则更新排序为1
                            mate.setMatesort(1);
                            sciTechnologyDemandMateRepository.save(mate);
                        }
                    }
                }
            }
        }

        if (list != null && list.size() > 0) {
            for (SciPersonnelInfo sciPersonnelInfo : list) {
                List<SciTechnologyDemandMate> lists = sciTechnologyDemandMateRepository.findBySpIdTdId(sciPersonnelInfo.getId(), tdId);
                if (lists != null && lists.size() > 0) {
                    //存在不操作
                } else {
                    if (!listModelIds.contains(sciPersonnelInfo.getId())){
                        SciTechnologyDemandMate sciTechnologyDemandMate = new SciTechnologyDemandMate();
                        sciTechnologyDemandMate.setTechnology(sciPersonnelInfo.getTechnology());
                        sciTechnologyDemandMate.setRetype(sciPersonnelInfo.getMatype());
                        sciTechnologyDemandMate.setMateTime(new Timestamp(new Date().getTime()));
                        sciTechnologyDemandMate.setSpId(sciPersonnelInfo.getId());
                        sciTechnologyDemandMate.setTdId(tdId);
                        sciTechnologyDemandMate.setIsSelect(0);
                        sciTechnologyDemandMate.setMatesort(1);
                        sciTechnologyDemandMateRepository.save(sciTechnologyDemandMate);
                    }
                }
            }
        }
        List<SciPersonnelInfo> list2 = spRepository.findNormalByTechnologyRetype(technology, sretype, shtg);
        if (list2 != null && list2.size() > 0) {
            for (SciPersonnelInfo sciPersonnelInfo : list2) {
                List<SciTechnologyDemandMate> lists = sciTechnologyDemandMateRepository.findBySpIdTdId(sciPersonnelInfo.getId(), tdId);
                if (lists != null && lists.size() > 0) {
                    //存在不操作
                } else {
                    if (!listModelIds.contains(sciPersonnelInfo.getId())) {
                        SciTechnologyDemandMate sciTechnologyDemandMate = new SciTechnologyDemandMate();
                        sciTechnologyDemandMate.setTechnology(sciPersonnelInfo.getTechnology());
                        sciTechnologyDemandMate.setRetype(sciPersonnelInfo.getMatype());
                        sciTechnologyDemandMate.setMateTime(new Timestamp(new Date().getTime()));
                        sciTechnologyDemandMate.setSpId(sciPersonnelInfo.getId());
                        sciTechnologyDemandMate.setTdId(tdId);
                        sciTechnologyDemandMate.setIsSelect(0);
                        sciTechnologyDemandMate.setMatesort(2);
                        sciTechnologyDemandMateRepository.save(sciTechnologyDemandMate);
                    }
                }
            }
        }

        List<SciPersonnelInfo> list3 = spRepository.findNormalByLikeTechnology(technology, shtg);
        if (list3 != null && list3.size() > 0) {
            for (SciPersonnelInfo sciPersonnelInfo : list3) {
                List<SciTechnologyDemandMate> lists = sciTechnologyDemandMateRepository.findBySpIdTdId(sciPersonnelInfo.getId(), tdId);
                if (lists != null && lists.size() > 0) {
                    //存在不操作
                } else {
                    if (!listModelIds.contains(sciPersonnelInfo.getId())) {
                        SciTechnologyDemandMate sciTechnologyDemandMate = new SciTechnologyDemandMate();
                        sciTechnologyDemandMate.setTechnology(sciPersonnelInfo.getTechnology());
                        sciTechnologyDemandMate.setRetype(sciPersonnelInfo.getMatype());
                        sciTechnologyDemandMate.setMateTime(new Timestamp(new Date().getTime()));
                        sciTechnologyDemandMate.setSpId(sciPersonnelInfo.getId());
                        sciTechnologyDemandMate.setTdId(tdId);
                        sciTechnologyDemandMate.setIsSelect(0);
                        sciTechnologyDemandMate.setMatesort(3);
                        sciTechnologyDemandMateRepository.save(sciTechnologyDemandMate);
                    }
                }
            }
        }
        //TODO查数据库此需求是否有匹配过有则返回list
        /*List<SciTechnologyDemandMate> listDemandMates = sciTechnologyDemandMateRepository.findByTdId(sciTechnologyDemand.getId());
        if (listDemandMates != null && listDemandMates.size() > 0) {
            for (SciTechnologyDemandMate sciTechnologyDemandMate : listDemandMates) {
                Integer spId = sciTechnologyDemandMate.getSpId();
                Optional<SciPersonnelInfo> ops = spRepository.findById(spId);
                if (ops.isPresent()) {
                    SciPersonnelInfo sciPersonnelInfo = ops.get();
                    result.add(spMapper.toDto(sciPersonnelInfo));
                }
            }
            return result;
        } else {
            throw new BadRequestException("未匹配到符合的对应类型");
        }*/

        Page<SciTechnologyDemandMate> pages = sciTechnologyDemandMateRepository.findByTdIdPage(criteria.getTdId(), pageable);
        Page<SciTechnologyDemandMateDto> map = pages.map(sciTechnologyDemandMateMapper::toDto);
        List<SciTechnologyDemandMateDto> lists = map.getContent();
        if (lists != null && lists.size() > 0) {
            for (SciTechnologyDemandMateDto sciTechnologyDemandMateDto : lists) {
                Integer spId = sciTechnologyDemandMateDto.getSpId();
                Optional<SciPersonnelInfo> ops = spRepository.findById(spId);
                if (ops.isPresent()) {
                    SciPersonnelInfo sciPersonnelInfo = ops.get();
                    sciTechnologyDemandMateDto.setSciPersonnelInfoDto(spMapper.toDto(sciPersonnelInfo));
                }
            }
        }
        return PageUtil.toPage(map);
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(SciTechnologyDemandMate resources) {
        SciTechnologyDemandMate sciTechnologyDemandMate = sciTechnologyDemandMateRepository.findById(resources.getId()).orElseGet(SciTechnologyDemandMate::new);
        ValidationUtil.isNull(sciTechnologyDemandMate.getId(), "SciTechnologyDemandMate", "id", resources.getId());
        sciTechnologyDemandMate.copy(resources);
        sciTechnologyDemandMateRepository.save(sciTechnologyDemandMate);
    }


    @Transactional(rollbackFor = Exception.class)
    public void select(ListSelectModelDto2 list) {
        if (list == null) {
            throw new BadRequestException("未找到匹配集合列表");
        }
        List<SelectModelDto2> res = list.getLists();
        for (SelectModelDto2 dto : res) {
            Integer id = dto.getId();
            Optional<SciTechnologyDemandMate> ops = sciTechnologyDemandMateRepository.findById(id);
            if (ops.isPresent()) {
                SciTechnologyDemandMate sciTechnologyDemandMate = ops.get();
                sciTechnologyDemandMate.setIsSelect(1);
                SciTechnologyDemandMate save = sciTechnologyDemandMateRepository.save(sciTechnologyDemandMate);
                //todo 需求选中劳模  若选中 则在劳模选中表中 新增或编辑 为选中状态
                Integer spId = save.getSpId();
                Integer tdId = save.getTdId();
                List<SciPersonnelInfoMate> listModelMate = sciPersonnelInfoMateRepository.findBySpIdTdId(spId, tdId);
                if (listModelMate != null && listModelMate.size() == 1) {
                    SciPersonnelInfoMate sciPersonnelInfoMate = listModelMate.get(0);
                    sciPersonnelInfoMate.setIsSelect(1);
                    sciPersonnelInfoMate.setMatesort(-1);//最高级顺序
                    sciPersonnelInfoMate.setMateTime(new Timestamp(new Date().getTime()));
                    sciPersonnelInfoMateRepository.save(sciPersonnelInfoMate);//设置为选中状态
                } else {
                    if (listModelMate == null || listModelMate.size() == 0) {
                        SciPersonnelInfoMate sciPersonnelInfoMate = new SciPersonnelInfoMate();
                        sciPersonnelInfoMate.setIsSelect(1);
                        sciPersonnelInfoMate.setSpId(spId);
                        sciPersonnelInfoMate.setTdId(tdId);
                        sciPersonnelInfoMate.setMatesort(-1);//最高级顺序
                        sciPersonnelInfoMate.setMateTime(new Timestamp(new Date().getTime()));
                        sciPersonnelInfoMateRepository.save(sciPersonnelInfoMate);//设置为选中状态
                    }
                }
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void cancelSelect(ListSelectModelDto2 list) {
        if (list == null) {
            throw new BadRequestException("未找到匹配集合列表");
        }
        List<SelectModelDto2> res = list.getLists();
        for (SelectModelDto2 dto : res) {
            Integer id = dto.getId();
            Optional<SciTechnologyDemandMate> ops = sciTechnologyDemandMateRepository.findById(id);
            if (ops.isPresent()) {
                SciTechnologyDemandMate sciTechnologyDemandMate = ops.get();
                sciTechnologyDemandMate.setIsSelect(0);
                SciTechnologyDemandMate save = sciTechnologyDemandMateRepository.save(sciTechnologyDemandMate);
                Integer spId = save.getSpId();
                Integer tdId = save.getTdId();
                //取消选则
                List<SciPersonnelInfoMate> listModelMate = sciPersonnelInfoMateRepository.findBySpIdTdId(spId, tdId);
                if (listModelMate != null && listModelMate.size() == 1) {
                    SciPersonnelInfoMate sciPersonnelInfoMate = listModelMate.get(0);
                    sciPersonnelInfoMate.setIsSelect(0);//取消选择
                    //sciPersonnelInfoMate.setMateSort(-1);
                    sciPersonnelInfoMate.setMateTime(new Timestamp(new Date().getTime()));
                    sciPersonnelInfoMateRepository.save(sciPersonnelInfoMate);
                } else {
                    if (listModelMate == null || listModelMate.size() == 0) {
                        SciPersonnelInfoMate sciPersonnelInfoMate = new SciPersonnelInfoMate();
                        sciPersonnelInfoMate.setIsSelect(0);
                        sciPersonnelInfoMate.setSpId(spId);
                        sciPersonnelInfoMate.setTdId(tdId);
                        //sciPersonnelInfoMate.setMateSort(-1);
                        sciPersonnelInfoMate.setMateTime(new Timestamp(new Date().getTime()));
                        sciPersonnelInfoMateRepository.save(sciPersonnelInfoMate);
                    }
                }
            }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void selecth5(ListSelectModelDto list) {
        if (list == null) {
            throw new BadRequestException("未找到匹配集合列表");
        }
        if (list.getListModelIdWithTdId() == null) {
            throw new BadRequestException("未找到匹配集合列表");
        }
        if (list.getListModelIdWithTdId().size() < 0) {
            throw new BadRequestException("未找到匹配集合列表");
        }
        List<SelectModelDto> res = list.getListModelIdWithTdId();
        for (SelectModelDto dto : res) {
            Integer modelId = dto.getModelId();
            Integer tdId = dto.getTdId();
            Optional<SciTechnologyDemand> ops1 = tdRepository.findById(tdId);
            Optional<SciPersonnelInfo> ops2 = spRepository.findById(modelId);
            if (ops1.isPresent() && ops2.isPresent()) {
                List<SciTechnologyDemandMate> result = sciTechnologyDemandMateRepository.findBySpIdTdId(modelId, tdId);
                if (result != null && result.size() == 1) {
                    SciTechnologyDemandMate sciTechnologyDemandMate = result.get(0);
                    sciTechnologyDemandMate.setIsSelect(1);
                    sciTechnologyDemandMateRepository.save(sciTechnologyDemandMate);
                }
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void cancelSelecth5(ListSelectModelDto list) {
        if (list == null) {
            throw new BadRequestException("未找到匹配集合列表");
        }
        if (list.getListModelIdWithTdId() == null) {
            throw new BadRequestException("未找到匹配集合列表");
        }
        if (list.getListModelIdWithTdId().size() < 0) {
            throw new BadRequestException("未找到匹配集合列表");
        }
        List<SelectModelDto> res = list.getListModelIdWithTdId();
        for (SelectModelDto dto : res) {
            Integer modelId = dto.getModelId();
            Integer tdId = dto.getTdId();
            Optional<SciTechnologyDemand> ops1 = tdRepository.findById(tdId);
            Optional<SciPersonnelInfo> ops2 = spRepository.findById(modelId);
            if (ops1.isPresent() && ops2.isPresent()) {
                List<SciTechnologyDemandMate> result = sciTechnologyDemandMateRepository.findBySpIdTdId(modelId, tdId);
                if (result != null && result.size() == 1) {
                    SciTechnologyDemandMate sciTechnologyDemandMate = result.get(0);
                    sciTechnologyDemandMate.setIsSelect(0);
                    sciTechnologyDemandMateRepository.save(sciTechnologyDemandMate);
                }
            }
        }
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            sciTechnologyDemandMateRepository.deleteById(id);
        }
    }

    public void download(List<SciTechnologyDemandMateDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SciTechnologyDemandMateDto sciTechnologyDemandMate : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("企业需求id", sciTechnologyDemandMate.getTdId());
            map.put("匹配时间", sciTechnologyDemandMate.getMateTime());
            map.put("匹配的技术领域", sciTechnologyDemandMate.getTechnology());
            map.put("匹配的需求类别", sciTechnologyDemandMate.getRetype());
            map.put("匹配上的劳模工匠", sciTechnologyDemandMate.getSpId());
            map.put("匹配顺序后台匹配排序", sciTechnologyDemandMate.getMatesort());
            map.put("是否选中", sciTechnologyDemandMate.getIsSelect());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}